<template>
  <h2 class="text-3xl font-semibold leading-7 text-gray-900 mb-10">
    {{ $t('pageVirtualMedia.virtualMediaSubTitleFirst') }}
  </h2>

  <el-row>
    <el-col v-for="(dev, $index) in proxyDevices" :key="$index" md="6">
      <h2 class="text-base font-semibold leading-7 text-gray-900">
        {{ dev.id }}
      </h2>
      <form-file v-if="!dev.isActive" :id="concatId(dev.id)" v-model="dev.file">
        <template #invalid>
          <b-form-invalid-feedback role="alert">
            {{ $t('global.form.required') }}
          </b-form-invalid-feedback>
        </template>
      </form-file>
      <el-upload
        v-if="!dev.isActive"
        ref="upload"
        :id="concatId(dev.id)"
        :limit="1"
        :auto-upload="false"
        v-model="dev.file"
      >
        <template #trigger>
          <el-button type="primary" class="mr-3">{{
            $t('global.fileUpload.browseText')
          }}</el-button>
        </template>
        <el-button
          v-if="!dev.isActive"
          type="success"
          :disabled="!dev.file"
          @click="startVM(dev)"
        >
          {{ $t('pageVirtualMedia.start') }}
        </el-button>
        <el-button
          v-if="dev.isActive"
          type="danger"
          :disabled="!dev.file"
          @click="stopVM(dev)"
        >
          {{ $t('pageVirtualMedia.stop') }}
        </el-button>
        <template #tip>
          <div class="el-upload__tip text-red">
            {{ $t('pageFirmware.form.updateFirmware.exceedTip') }}
          </div>
        </template>
      </el-upload>
    </el-col>
  </el-row>

  <h2
    v-if="loadImageFromExternalServer"
    class="text-3xl font-semibold leading-7 text-gray-900 mt-10"
  >
    {{ $t('pageVirtualMedia.virtualMediaSubTitleSecond') }}
  </h2>

  <el-row v-if="loadImageFromExternalServer" class="mt-4">
    <el-row>
      <el-col v-for="(device, $index) in legacyDevices" :key="$index" md="6">
        <h2 class="text-base font-semibold leading-7 text-gray-900">
          {{ device.id }}
        </h2>
        <el-button
          type="primary"
          :disabled="device.isActive"
          @click="configureConnection(device)"
        >
          {{ $t('pageVirtualMedia.configureConnection') }}
        </el-button>

        <el-button
          v-if="!device.isActive"
          type="success"
          class="float-right"
          :disabled="!device.serverUri"
          @click="startLegacy(device)"
        >
          {{ $t('pageVirtualMedia.start') }}
        </el-button>
        <el-button
          v-if="device.isActive"
          type="danger"
          class="float-right"
          @click="stopLegacy(device)"
        >
          {{ $t('pageVirtualMedia.stop') }}
        </el-button>
      </el-col>
    </el-row>
  </el-row>
  <modal-configure-connection-vue
    ref="modal"
    :connection="modalConfigureConnection"
    @ok="saveConnection"
  />
</template>

<script setup lang="ts">
import { useVirtualMediaStore } from '@/store/ServicesManagement/VirtualMedia/VirtualMediaStore';
import { useI18n } from 'vue-i18n';
import NbdServer from '@/utilities/NBDServer';
import modalConfigureConnectionVue from './ModalConfigureConnection.vue';
import { useAuthenticationStore } from '@/store/Authentication/Authentication';

const virtualMediaStore = useVirtualMediaStore();
const i18n = useI18n();
const modalConfigureConnection = ref();
const authenticationStore = useAuthenticationStore();
const loadImageFromExternalServer =
  import.meta.env.VUE_APP_VIRTUAL_MEDIA_LIST_ENABLED === 'true' ? true : false;
const proxyDevices = computed(() => {
  return virtualMediaStore.proxyDevices;
});
const legacyDevices = computed(() => {
  return virtualMediaStore.legacyDevices;
});
const modal = ref();

onMounted(() => {
  if (proxyDevices.value.length > 0 || legacyDevices.value.length > 0) return;
  virtualMediaStore.getData();
});

const startVM = (device: {
  nbd: NbdServer;
  websocket: any;
  file: typeof device.nbd.file | null;
  id: any;
  isActive: boolean;
}) => {
  const token = authenticationStore.token as string;
  device.nbd = new NbdServer(
    `wss://${window.location.host}${device.websocket}`,
    device.file as { size: number },
    device.id,
    token,
  );
  ElNotification({
    title: 'Success',
    message: i18n.t('pageVirtualMedia.toast.serverRunning'),
    type: 'success',
  });
  device.nbd.errorReadingFile = () =>
    ElNotification({
      title: 'Error',
      message: i18n.t('pageVirtualMedia.toast.errorReadingFile'),
      type: 'error',
    });
  device.nbd.socketClosed = (ev: CloseEvent) => {
    if (ev.reason == 'Session already connected') {
      ElNotification({
        title: 'Error',
        message: i18n.t('pageVirtualMedia.toast.sessionAlreadyConnected'),
        type: 'error',
      });
    } else if (ev.code === 1000)
      ElNotification({
        title: 'Success',
        message: i18n.t('pageVirtualMedia.toast.serverClosedSuccessfully'),
        type: 'success',
      });
    else
      ElNotification({
        title: 'Error',
        message: i18n.t('pageVirtualMedia.toast.serverClosedWithErrors'),
        type: 'error',
      });
    device.file = null;
    device.isActive = false;
  };

  device.nbd.start();
  device.isActive = true;
};
const stopVM = (device: { nbd: { stop: () => void } }) => {
  device.nbd.stop();
};

const startLegacy = (connectionData: {
  serverUri: any;
  username: any;
  password: any;
  isRW: boolean;
  id: any;
  isActive: boolean;
}) => {
  var data: {
    Image: typeof connectionData.serverUri;
    UserName: typeof connectionData.username;
    Password: typeof connectionData.password;
    WriteProtected: typeof connectionData.isRW;
  } = {
    Image: connectionData.serverUri,
    UserName: connectionData.username,
    Password: connectionData.password,
    WriteProtected: !connectionData.isRW,
  };
  virtualMediaStore
    .mountImage({
      id: connectionData.id,
      data: data,
    })
    .then(() => {
      ElNotification({
        title: 'Success',
        message: i18n.t('pageVirtualMedia.toast.serverConnectionEstablished'),
        type: 'success',
      });
      connectionData.isActive = true;
    })
    .catch(() => {
      ElNotification({
        title: 'Error',
        message: i18n.t('pageVirtualMedia.toast.errorMounting'),
        type: 'error',
      });
      connectionData.isActive = false;
    });
};
const stopLegacy = (connectionData: { id: any; isActive: boolean }) => {
  virtualMediaStore
    .unmountImage(connectionData.id)
    .then(() => {
      ElNotification({
        title: 'Success',
        message: i18n.t('pageVirtualMedia.toast.serverClosedSuccessfully'),
        type: 'success',
      });
      connectionData.isActive = false;
    })
    .catch(() =>
      ElNotification({
        title: 'Error',
        message: i18n.t('pageVirtualMedia.toast.errorUnmounting'),
        type: 'error',
      }),
    );
};
const saveConnection = (connectionData: {
  serverUri: any;
  username: any;
  password: any;
  isRW: any;
}) => {
  modalConfigureConnection.value.serverUri = connectionData.serverUri;
  modalConfigureConnection.value.username = connectionData.username;
  modalConfigureConnection.value.password = connectionData.password;
  modalConfigureConnection.value.isRW = connectionData.isRW;
};
const configureConnection = (connectionData: any) => {
  modalConfigureConnection.value = connectionData;
  modal.value.visiable = true;
};
const concatId = (val: string) => {
  return val.split(' ').join('_').toLowerCase();
};
</script>
